package com.kingyun.gpsinspection.purificationservice.services.tdm.innerservice.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.kingyun.gpsinspection.purificationservice.common.utils.ConstantUtil;
import com.kingyun.gpsinspection.purificationservice.common.utils.FileTypeUtil;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.tdm.TdmFileMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.tdm.TaskLinkMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.tdm.TdmWorkOrderMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.tdm.WorkPermitMapper;
import com.kingyun.gpsinspection.purificationservice.facade.model.File;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.EmployeeVo;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.RedisValue;
import com.kingyun.gpsinspection.purificationservice.facade.model.tdm.TaskLink;
import com.kingyun.gpsinspection.purificationservice.facade.model.tdm.WorkOrderVo;
import com.kingyun.gpsinspection.purificationservice.facade.model.tdm.WorkPermit;
import com.kingyun.gpsinspection.purificationservice.facade.model.tdm.WorkPermitVo;
import com.kingyun.gpsinspection.purificationservice.facade.service.tdm.IBMBPMService;
import com.kingyun.gpsinspection.purificationservice.facade.service.tdm.TaskLinkService;
import com.kingyun.gpsinspection.purificationservice.facade.service.tdm.WorkOrderService;
import com.kingyun.gpsinspection.purificationservice.facade.service.tdm.WorkPermitService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * Created by liyi on 2016/12/15.
 */
public class WorkPermitServiceImpl implements WorkPermitService{
    public Logger logger = LoggerFactory.getLogger(this.getClass());
    // BPM
    @Autowired
    public IBMBPMService ibmbpmService;
    @Autowired
    public WorkPermitMapper workPermitMapper;
    @Autowired
    public WorkOrderService workOrderService;
    @Autowired
    private TdmFileMapper tdmFileMapper;
    @Autowired
    public TaskLinkService taskLinkService;
    @Autowired
    public TaskLinkMapper taskLinkMapper;
    @Autowired
    public TdmWorkOrderMapper tdmWorkOrderMapper;

    /**
     * 新增作业许可并发起流程
     *
     * @param employeeVo
     * @param workPermit
     * @param uploadFiles
     * @param deletedFiles
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public WorkPermit saveWorkPermit(RedisValue redisValue, EmployeeVo employeeVo, WorkPermit workPermit, String uploadFiles, String deletedFiles, List<WorkOrderVo> workOrderList){
        //发起流程 1、开启流程（调用BPM开启流程接口）URL 为BPM API方法
        /*String username="deadmin";
        String password="deadmin";*/
        //用户名
        String username = redisValue.getLoginName();
        //密码
        String password = redisValue.getPassWord();
        String result= ibmbpmService.openBPM(employeeVo, (short)8, username, password, null);
        //如果没有权限直接返回null
        if (result.equals("WorkSpaceError")) {
            return null;
        }
        //流程实例ID
        String piid=null;
        //任务节点ID
        String tkiid=null;
        //任务节点名
        String name=null;
        JSONObject resultObj=JSONObject.parseObject(result);
        //获取data属性的值
        JSONObject dataObj=(JSONObject)resultObj.get("data");
        //获取tasks属性的值
        JSONArray itemsArray=(JSONArray)dataObj.get("tasks");
        //循环json数组
        for (int i = 0; i < itemsArray.size(); i++) {
            //得到json对象
            JSONObject ob  = (JSONObject) itemsArray.get(i);
            //piid这里是列名称，获取json对象中列名为piid的值
            piid= ob.getString("piid");
            //tkiid这里是列名称，获取json对象中列名为tkiid的值
            tkiid= ob.getString("tkiid");
            //name这里是列名称，获取json对象中列名为name的值
            name= ob.getString("name");
        }

        // 完成当前节点，往下一节点扭转
        result = ibmbpmService.completeTask(username, password, tkiid, null);

        //处理返回值为空串：执行了但是没有返回值
        if ("".equals(result)) {
            logger.info("完成作业许可流程第一个任务节点返回值为空串！");
        } else {
            //获得返回值
            resultObj = JSONObject.parseObject(result);
            if (resultObj != null) {
                String status = (String) resultObj.get("status");
                //开始流程成功
                if (status != null && status.equals("200")) {
                    //设置ID
                    workPermit.setWorkPermitId(UniqueUtil.uuid());
                    //设置创建人ID
                    workPermit.setCreateUserId(employeeVo.getEmployeeId());
                    //设置创建时间
                    workPermit.setCreateTime(new Date());
                    //设置修改人ID
                    workPermit.setModifyUserId(employeeVo.getEmployeeId());
                    //设置修改时间
                    workPermit.setModifyTime(new Date());
                    //状态1是正常；0是删除
                    workPermit.setIsDelete((short) 1);
                    //状态1是启用；0是关闭
                    workPermit.setIsEnable((short) 1);
                    //流程ID
                    workPermit.setFlowId(piid);
                    //设置任务状态
                    workPermit.setTaskStatus((short) 1);
                    workPermitMapper.insertSelective(workPermit);

                    //保存附件
                    saveAttach(workPermit, uploadFiles, deletedFiles);

                    //添加任务环节
                    TaskLink taskLink = new TaskLink();
                    //流程实例ID
                    taskLink.setPiPiid(piid);
                    //任务节点ID
                    taskLink.setTkiid(tkiid);
                    //任务类型
                    taskLink.setTaskType(workPermit.getTaskType());
                    //任务ID
                    taskLink.setTaskId(workPermit.getWorkPermitId());
                    //节点名称
                    taskLink.setTaskLinkName(name);
                    //节点
                    taskLink.setNode(workPermit.getNode());
                    // 设置ID
                    taskLink.setTaskLinkId(UniqueUtil.uuid());
                    // 设置人员ID
                    taskLink.setUserId(employeeVo.getEmployeeId());
                    // 执行人组织
                    taskLink.setOrgId(employeeVo.getOrgId());
                    // 保存任务环节
                    taskLinkMapper.insertNew(taskLink);

                    //保存工单：删除旧工单，新增新工单
                    workOrderService.saveWorkOrderList(employeeVo, taskLink, workOrderList);

                } else {
                    logger.error("完成作业许可流程第一个任务节点返回状态非200！");
                }
            } else {
                logger.error("完成作业许可流程第一个任务节点返回值非json字符串！");
            }
        }

        return workPermit;
    }

    /**
     * 保存附件
     * @param workPermit
     * @param uploadFiles
     * @param deletedFiles
     */
    public  void saveAttach(WorkPermit workPermit, String uploadFiles, String deletedFiles){
        //保存附件
        if (StringUtils.isNotBlank(uploadFiles)) {
            //强制转换成集合
            List<File> listFiles = JSON.parseArray(uploadFiles, File.class);
            //重新设置附件属性
            for (int i = 0; i < listFiles.size(); i++) {
                File _file = listFiles.get(i);
                //设置主键
                _file.setFileId(UniqueUtil.uuid());
                //设置业务数据id
                _file.setBusinessId(workPermit.getWorkPermitId());
                _file.setFileType((short) FileTypeUtil.getFileTypeByFileName(_file.getFileName()));
            }
            //必须判断非空
            if (listFiles != null && listFiles.size() > 0) {
                tdmFileMapper.insertByList(listFiles);
            }
        }
        //需要删除的附件信息
        if(StringUtils.isNotBlank(deletedFiles)){
            //强制转换成集合
            List<File> listFiles =  JSON.parseArray(deletedFiles,File.class);
            if(listFiles!=null && listFiles.size()>0){
                int len = listFiles.size();
                for(int i=0;i<len;i++){
                    File _file = listFiles.get(i);
                    tdmFileMapper.deleteByPrimaryKey(_file.getFileId());
                }
            }
        }
    }

    @Override
    public WorkPermitVo findWorkPermit(String piid) throws Exception {
        if(StringUtils.isBlank(piid)){
            return null;
        }

        //根据任务ID查询作业许可信息
        WorkPermitVo workPermitVo= workPermitMapper.findWorkPermitByPiid(piid);

        return workPermitVo;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int updateById(TaskLink taskLink,Short node, String workPermitId) throws Exception {
        //根据变更id查询变更信息
        WorkPermit workPermit=workPermitMapper.selectByPrimaryKey(workPermitId);
        //设置节点
        workPermit.setNode(node);
        //任务状态
        if (ConstantUtil.WORK_PERMIT.equals(taskLink.getTaskLinkName())) {
            workPermit.setTaskStatus((short) 3);
            workPermit.setFinishTime(new Date());
        }
        //修改变更信息
        return workPermitMapper.updateByPrimaryKeySelective(workPermit);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int disposeTask(RedisValue redisValue,EmployeeVo employeeVo, WorkPermit workPermit, List<WorkOrderVo> workOrderList, TaskLink taskLink) {
        //标志变量
        int a = 0;

        String param = null;
        try {
            //判断审批状态、项目类型
            if (taskLink.getAuditStatus() != null && !taskLink.getAuditStatus().equals("")) {
                //流程走向参数
                String val = "{\"type\":\"" + taskLink.getAuditStatus() + "\"}";
                //转换成utf-8
                param = URLEncoder.encode(val, "utf-8");
                //审核状态
                taskLink.setAuditStatus(taskLink.getAuditStatus());
                //判断审批状态、项目级别
            }
            if (workPermit.getIsAClass() != null && !workPermit.getIsAClass().equals("")) {
                //流程走向参数
                String val = "{\"type\":\"" + workPermit.getIsAClass() + "\"}";
                //转换成utf-8
                param = URLEncoder.encode(val, "utf-8");
            }
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        }

        //用户信息
       /* String username = "deadmin";
        String password = "deadmin";*/
        //用户名
        String username = redisValue.getLoginName();
        //密码
        String password = redisValue.getPassWord();
        //完成当前节点，往下一节点扭转
        String result = ibmbpmService.completeTask(username, password, taskLink.getTkiid(), param);

        //获得返回值
        JSONObject resultObj = JSONObject.parseObject(result);
        if (resultObj != null) {
            String status = (String) resultObj.get("status");
            //开始流程成功
            if (status != null && status.equals("200")) {
                if (!"作业许可证关闭".equals(taskLink.getTaskLinkName())) {
                    //保存工单：删除旧工单，新增新工单
                    a += workOrderService.saveWorkOrderList(employeeVo, taskLink, workOrderList);
                }

                //添加任务环节
                taskLink.setTaskLinkId(UniqueUtil.uuid());
                //任务发起表存的是当前节点
                taskLink.setNode(workPermit.getNode());
                taskLink.setTaskType(workPermit.getTaskType());
                taskLink.setTaskId(workPermit.getWorkPermitId());
                // 设置人员ID
                taskLink.setUserId(employeeVo.getEmployeeId());
                // 执行人组织
                taskLink.setOrgId(employeeVo.getOrgId());
                a += taskLinkMapper.insertNew(taskLink);
            } else {
                logger.error("完成“" + taskLink.getTaskLinkName() + "”返回状态非200！");
            }
        } else {
            logger.error("完成“" + taskLink.getTaskLinkName() + "”返回值非json字符串！");
        }

        return a;
    }

    /**
     * 根据主键查询
     * @param id
     * @return
     */
    @Override
    public WorkPermitVo queryByPrimaryKey(String id) {
        WorkPermitVo workPermit = workPermitMapper.selectByPrimaryKey(id);
        return workPermit;
    }
}
